window.addEventListener('DOMContentLoaded', () => {
  isStuLogin();
});

function loadPage() {
  setTimeout(() => {
    loadTestPaper(app.pageHelper.global_page, app.pageHelper.global_limit, $('.layui-nav img').attr('alt'));
    loadAllClazz();
  }, 300)
}

function loadTestPaper(page, limit, stuId) {
  $.get(`${app.urlLocation.queryTestPaperIsDone}`, {page: page, limit: limit, stuId: stuId}, res => {
    let data = res.data;
    let testItemHtml = '';
    $.each(data, (i, v) => {
      testItemHtml += returnTestItemHtml(v);
    });
    $('.question-box .layui-row').append(testItemHtml);
  })
}

function showMoreTestPaper() {
  app.pageHelper.global_page++;
  loadTestPaper(app.pageHelper.global_page, app.pageHelper.global_limit);
}

function showDetail(elem) {
  layui.use(['layer'], () => {
    let layer = layui.layer;
    let testId = elem.find('.test-id').text();
    let isDone = elem.find('.is-done').text();
    localStorage.setItem('testId', testId);
    switch (isDone) {
      case '已做':
        window.location.href = '/student-action/test-detail';
        break;
      case '未做':
        layer.confirm('开始答题后未在规定时间内答完或切换页面将记为0分，是否开始答题?', {
          btn: ['开始', '等会儿']
        }, () => {
          window.location.href = '/student-action/do-test';
        });
        break;
    }
  })
}

function returnTestItemHtml(testPapers) {
  let flag = testPapers.isDone === 2 ? '未做' : '已做';
  return `<div class="layui-col-lg3 test-item" onclick="showDetail($(this))">` +
    `<div class="item-box">` +
    `<span class="test-id layui-hide">${testPapers.testId}</span>` +
    `<span class="test-title">${testPapers.testTitle}</span>` +
    `<span class="test-clazz">${testPapers.testClazz}</span>` +
    `<span class="sum-scale">总分值：${testPapers.sumScale}分</span>` +
    `<span class="test-time">考试时长：${testPapers.testTime}分钟</span>` +
    `<span class="layui-badge layui-bg-blue is-done">${flag}</span>` +
    `</div>` +
    `</div>`;
}

function loadAllClazz() {
  layui.use(['element', 'form'], () => {
    $.get(`${app.urlLocation.queryAllCt}`, res => {
      $.each(res, (i, v) => {
        $('.question-action .layui-form-item:eq(1) select').append(`<option value="${v.id}">${v.classType}</option>`);
      });
      app.resetForm();
    });
  });
}